<template>
  <view class="content">
    <view class="login-bg">
			<image class="bg" src="../../static/login.png"></image>
      <view class="login-title">workly</view>
    </view>
    <view class="login-btn">
      <u-button type="primary" shape="circle" :loading="loading" @click="login">使用微信登录</u-button>
    </view>
  </view>
</template>

<script>
import api from '@/api/api.js'
export default {
  data() {
    return {
      code: '',
			openid: '',
			session_key: '',
      loading: false
    };
  },
  onShow () {},
  methods: {
		login () {
			// 点击按钮触发登录事件
			wx.login({
				success: res => {
					// 获取临时登录凭证
					const code = res.code;
					const openid = uni.getStorageSync('openid');
					uni.showLoading({
						title: '登录中...',
						mask: true
					});
					wx.getUserInfo({
						success: async r => {
							const data = {
								code: code,
								iv: r.iv,
								encryptedData: r.encryptedData
							}
							const res = await api.login(data);
							console.log(res, 'res======')
							uni.hideLoading();
							this.openid = res.openid;
							this.session_key = res.session_key;
							// 将服务器返回的自定义登录态 token 存储到本地
							wx.setStorageSync('openid', this.openid);
							wx.setStorageSync('session_key', this.session_key);
							// 判断是否已登录
							const res2 = await api.getUserByOpenId({ openId: this.openid });
							console.log(res2,'res2======')
							if (res2.code === 0) {
								const userinfo = res2.userinfo;
								if (!userinfo.phonenum) {
									// uni.navigateTo({
									// 	url: '/pages/login/register'
									// })
								} else {
									uni.switchTab({
										url: '/pages/index/index'
									})
								}
							}
						},
						fail: error => {
							uni.hideLoading();
						}
					})
				}
			})
		}
  },
};
</script>

<style lang="scss">
.content {
  .login-btn {
    padding: 10upx 50upx;
    margin-top: 150upx;
  }
  
  .login-bg {
		.bg {
			width: 100%;
			height: 750upx;
		}
    .login-title {
      font-size: 60upx;
      color: #fff;
			text-shadow: 2px 2px 5px rgba(15, 15, 15, 0.48);
			text-align: center;
			margin-top: 30upx;
    }
  }
}
</style>
